package com.sw.paisong.security;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sw.paisong.util.Constants;
import com.sw.paisong.util.ServletUtils;
import com.sw.paisong.vo.JsonVO;

public class ShiroAuth extends FormAuthenticationFilter {
	private static final Logger logger = LoggerFactory.getLogger(ShiroAuth.class);

	@Override
	protected void redirectToLogin(ServletRequest request, ServletResponse response)
			throws IOException {

		HttpServletRequest req = WebUtils.toHttp(request);
		HttpServletResponse res = WebUtils.toHttp(response);
		if (req.getHeader("request-from") != null
				&& req.getHeader("request-from").equalsIgnoreCase("mobile")) {
			logger.debug("mobile!");
			JsonVO resJson = new JsonVO();
			resJson.setSuccess(false);
			resJson.setCode(Constants.CODE_LOGIN_FAILD);
			resJson.setMessage("Session timeout!");
			ServletUtils.responseJson(res, resJson);
			// res.getWriter().write("{success:false,message:'mobile session error'}");
			return;
		}
		if (req.getHeader("x-requested-with") != null
				&& req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
			res.setHeader("sessionStatus", "timeOut");
			res.getWriter().write("{success:false,message:'session error'}");
		} else {
			String loginUrl = getLoginUrl();
			WebUtils.issueRedirect(request, response, loginUrl);
		}
	}

}